import { EuiConfirmModal } from "@elastic/eui";
import { sizes } from "../styles/sizes";
import { useUserStore } from "../state/users.ts";
import { updateUserStatus } from "../commands/chats.ts";

interface MuteToggleModalProps {
  maybeReplyKey: string | null;
  closeModal: () => void;
  fetchUsersAndChats: () => Promise<void>;
}

export const MuteToggleModal = ({
  maybeReplyKey,
  closeModal,
  fetchUsersAndChats,
}: MuteToggleModalProps) => {
  if (!maybeReplyKey) {
    return null;
  }

  const userStore = useUserStore();
  const userInfo = userStore.getUserInfo();

  const currentUserStatus = userInfo[maybeReplyKey].status;
  const userAlias = userInfo[maybeReplyKey].alias;
  const userAutogeneratedName = userInfo[maybeReplyKey].displayName;

  const title =
    currentUserStatus === "ACTIVE" ? "Mute source" : "Unmute source";
  const text =
    currentUserStatus === "ACTIVE"
      ? `Muted sources will appear in the "Muted" tab. They
        will still be able to send you messages, but you will not receive
        notifications for them.`
      : `Do you want to unmute this source? New messsages from them will appear in your Inbox.`;

  const handleMuteUser = async () => {
    try {
      const newStatus = currentUserStatus === "ACTIVE" ? "MUTED" : "ACTIVE";
      await updateUserStatus(maybeReplyKey, newStatus);

      closeModal();

      await fetchUsersAndChats();
    } catch (e: unknown) {
      if (e instanceof Error) {
        console.error("Error handling user status change:", e.message);
      } else {
        console.error("Error handling user status change", e);
      }
    }
  };

  return (
    <EuiConfirmModal
      style={{ width: sizes.muteModal.width }}
      title={
        <div>
          {title}{" "}
          <i>
            {userAlias
              ? `${userAlias} (${userAutogeneratedName})`
              : userAutogeneratedName}
          </i>
          ?
        </div>
      }
      onCancel={closeModal}
      onConfirm={handleMuteUser}
      cancelButtonText="Cancel"
      confirmButtonText={title}
      buttonColor="primary"
    >
      <p>{text}</p>
    </EuiConfirmModal>
  );
};
